import UserModel from "@src/models/User"
import { INext, IReq, IRes } from "@src/routes/common/types"
import { resExample } from "@src/services/common/responseData"

import redisClient from "@src/redis/redis"

/**
 * 验证邮箱与用户是否匹配
 * @param req 
 * @param res 
 * @param next 
 */
export const validateEmail  = async (req: IReq, res: IRes, next: INext) => {
    const userId = req.userId
    const email = req.body.email
    // 说明用户可能在进行修改密码操作
    if (userId) {
        const model = await UserModel()
        const user = await model.findOne({
            where:{
                is:userId,
                email
            }
        })
        if (!user) {
            throw resExample({
                code: 400,
                message: '邮箱与用户不匹配',
                success: false,
                data: null
            })
        }
    }
    next()
}

/**
 * 验证验证码
 * @param req 
 * @param res 
 * @param next 
 */
export const validateCode = async (req: IReq, res: IRes, next: INext) => {
    const email = req.body.email
    const code = req.body.code
    const type = req.body.type ?? 'register'
    try{        
        const key = `verification_code:${email}:${type}`
        const redisCode = await redisClient.get(key)
        console.log('redisCode', redisCode,typeof redisCode);
        console.log('code', code, typeof code);
        
        
        if (!redisCode) {
            throw resExample({
                code: 400,
                message: '验证码已过期',
                success: false,
                data: null
            })
        }

        if (redisCode !== code+'') {
            throw resExample({
                code: 400,
                message: '验证码错误',
                success: false,
                data: null
            })
        }

        next()
    }catch(err){
        throw resExample({
            code: 400,
            message: '验证码验证失败',
            success: false,
            data: null
        })
    }
}